import axios from 'axios'
import { ShowLoading, ShowError, ShowSuccess } from './../utils/message';
import { Toast } from 'antd-mobile'


export const baseURL = 'http://localhost:3000/'

const request = axios.create({
    baseURL: baseURL,
    timeout: 60000,
    headers: {

    }
});


request.interceptors.request.use(function (config: any) {
    const token = sessionStorage.getItem('appToken') || ''
    if (token) {
        config.headers.token = token
    }

    // ShowLoading()
    return config;
}, function (error) {
    ShowError('网络异常')
    return Promise.reject(error);
});

request.interceptors.response.use(function (response) {

    Toast.clear()

    if (response.data.code == 200) {

    } else {
        ShowError(response.data.msg)
        if (response.data.code == 3001) {

        }
    }

    return response;
}, function (error) {
    ShowError('服务器异常 - 未知错误')
    return Promise.reject(error);
});


export const GetAction = (url: string, params?: object, headers?: object) => {
    return new Promise((resolve, reject) => {
        request({
            url,
            method: 'GET',
            params: params,
            headers,
        })
            .then(res => {
                resolve(res.data)
            })
            .catch(err => {
                reject(err)
            })
    })
}


export const PostAction = (url: string, data?: object, params?: object, headers?: object) => {
    return new Promise((resolve, reject) => {
        request({
            url,
            method: 'POST',
            data: data,
            params: params,
            headers,
        })
            .then(res => {
                resolve(res.data)
            })
            .catch(err => {
                reject(err)
            })
    })
}

export default request;